package com.tianpengtech.admin.feedback;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Model;
import com.tianpengtech.common.exception.ServiceException;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.admin.AbstractAdmin;
import com.tianpengtech.admin.IAdminOpt;
import com.tianpengtech.admin.opertion.OperationDao;
import com.tianpengtech.common.model.account.Account;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.feedback.FeedBack;
import com.tianpengtech.common.model.opertion.Opertion;
import com.tianpengtech.common.search.EqualCondition;
import com.tianpengtech.common.search.LikeCondition;
import com.tianpengtech.common.search.QueryConstructor;
import com.tianpengtech.common.util.XxxUtil;
import com.tianpengtech.common.validator.Validator;
import com.tianpengtech.common.validator.rules.numberic.NumbericMustBeEqual;
import com.tianpengtech.common.validator.rules.numberic.NumbericMustBeLessThan;
import com.tianpengtech.common.validator.rules.other.MustBeNotNull;

public class FeedBackAdminServiceImpl extends AbstractAdmin implements IAdminOpt{

	@Override
	public void beforeAdd(Model<?> model) throws ValidateException {

	}

	@Override
	public void beforeQueryById(Model<?> model, int id) {

	}

	@Override
	public void beforeUpdate(Model<?> model) throws ValidateException {

	}

	@Override
	public void beforeDelete(Model<?> model) {

	}

	@Override
	public void builderSQLExpected(Model< ? > model,
			QueryConstructor queryConstruct, Map< String, Object > params) {
		queryConstruct
		.and(new EqualCondition(FeedBack.DELETETAG, FeedBack.DELETE_STATUS_NO));
		String contact = model.getStr(FeedBack.CONTACT);
		if(StringUtils.isNotEmpty(contact)){
			queryConstruct
			.and(new LikeCondition(FeedBack.CONTACT,"%"+contact+"%"));
		}
	}

	@Override
	public String tableName() {
		return FeedBack.dao.tableName();
	}
	
	@Override
	public boolean deleteById(Model<?> model, int id) throws ValidateException, ServiceException {
		model.set(FeedBack.DELETETAG, FeedBack.DELETE_STATUS_YES);
		return model.update();
	}

	@Override
	public void changeStatus(Model<?> model, long id, int status, Kv params) throws ValidateException {
		
		Model<FeedBack> temp = FeedBack.dao.findById(id);
		Validator validator = new Validator();
		validator
			.addRule(new MustBeNotNull(temp, "当前就不存在"))
			.addRule(new NumbericMustBeLessThan(temp.getInt(FeedBack.STATUS), FeedBack.STATUS_SUCCESS, "当前反馈已经处理了，请勿重复处理"));
		validator.excute();
		temp.set(FeedBack.STATUS, status);
		temp.update();
		Account account = XxxUtil.readSessionInfo();
		long userId = account.getLong(Account.ID);
		if(status==FeedBack.STATUS_SUCCESS){
			String result = "【已经处理】"+temp.getStr(FeedBack.CONTACT)+"的反馈信息";
			OperationDao.ME.recordLog(id, Opertion.OPT_FEEDBACK_LOG,userId,result);
		}
	}

}